<template>
  <div id="qr">
    <div >
      <p>
        <label>
          二维码类型：
          <input type="radio" value="text" v-model="type"> 文本
          <input type="radio" value="web" v-model="type"> 网址
          <input type="radio" value="mail" v-model="type"> 邮箱
        </label>
      </p>
      <p>
        <label>
          请输入内容：
          <input v-model.trim="str"/>
        </label>
      </p>
      <p>
        <label>
          二维码边长：
          <input v-model.trim="len" value="140" type="range" max="600" min="80"/>
          {{len}}px
        </label>
      </p>
      <p style="text-align: right">
        <button @click="doit()">确定生成</button>
      </p>
    </div>
    <div id="qrcode"></div> <!-- 创建一个div，并设置id为qrcode -->
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2'  // 引入qrcode
  export default {
    name : 'qr',
    data() {
      return {
        type: "text",
        str: "",
        len: 100
      }
    },
    mounted () {
      this.type = this.getParam("type");
      this.str = this.getParam("str");
      this.len = this.getParam("len");
      if (this.type === "null") {
        this.type = "txt";
      }
      if (this.str === "null") {
        this.str = "这是示例文本";
      }
      if (this.len === "null") {
        this.len = 140;
      }
      this.qr();
    },
    methods: {
      qr() {
        var str = this.str;
        if (this.type === "web" && !str.startsWith("http")) {
          str="http://" + str;
        }
        if (this.type === "mail" && !str.startsWith("mailto:")) {
          str="mailto:" + str;
        }
        let qrcode = new QRCode('qrcode', {
          width: this.len,
          height: this.len,
          text: str, // 二维码地址
          colorDark : "#000",
          colorLight : "#FFF",
        })
      },
      getParam(name){
        return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
      },
      doit() {
        window.location.href='index.html?str='+this.str+"&len="+this.len+"&type="+this.type;
      }
    }
  }
</script>
<style>
  #qr {
    width: 300px;
    margin: 10px auto;
    text-align: left;
    background-color: #f5f5f5f5;
    padding: 30px;
    border-radius: 5px;
  }
  #qr:hover {
    -moz-box-shadow: 1px 1px 4px #909090;
    -webkit-box-shadow: 1px 1px 4px #909090;
    box-shadow:1px 1px 4px #909090;
  }
  #qrcode img {
    margin: 10px auto;
    padding: 10px;
  }
  input {
    margin: 2px;
    padding: 4px;
    border-radius: 4px;
    border: 1px solid #AAA;
  }
  button {
    border-radius: 5px;
    border: none;
    padding: 10px;
    background-color: #90909030;
    -moz-box-shadow: 1px 1px 4px #909090;
    -webkit-box-shadow: 1px 1px 4px #909090;
    box-shadow:1px 1px 4px #909090;
  }
</style>
